package com.prs.crm.service.impl;

import java.io.File;
import java.lang.reflect.ParameterizedType;

import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.prs.crm.context.Constrains;
import com.prs.crm.context.FileUtil;
import com.prs.crm.dao.BaseDao;
import com.prs.crm.domain.SimpleFlowEntity;
import com.prs.crm.domain.flow.FlowVerifyDetail;
import com.prs.crm.domain.hr.Person;
import com.prs.crm.domain.project.Task;
import com.prs.crm.flow.SimpleFlowListener;
import com.prs.crm.service.SimpleFlowService;

public abstract class SimpleFlowServiceImpl<T extends SimpleFlowEntity,K extends BaseDao<T>> extends BaseServiceImpl<T,K> implements SimpleFlowService<T>,SimpleFlowListener<T> {
	
	@Override
	public void save(T entity)
	{
		if (entity.getFlowstatus()==null)
		{
			entity.setFlowstatus(Constrains.WORKFLOWENTITY_STATE_NOT);
		}
		super.save(entity);
	}
	
	public void startFlow(T entity)
	{
		validateSubmit(entity);
		entity.setFlowstatus(Constrains.WORKFLOWENTITY_STATE_PROCESS);
		super.save(entity);
	}
	
	public void executeVerify(T entity,FlowVerifyDetail detail,Person exeutor,File file,String filename)
	{
		detail.setAttach(FileUtil.getInstance().createAttach(file, filename));
		detail.setExecutor(exeutor);
		entity.addVerifyDetail(detail);
		if (detail.getResult()==Constrains.WORKFLOWPROCESS_RESULT_PASS)
			entity.setFlowstatus(Constrains.WORKFLOWENTITY_STATE_VALID);
		else
			entity.setFlowstatus(Constrains.WORKFLOWENTITY_STATE_INVALID);
		super.save(entity);
		onFlowEnd(entity);
	}
	
	public PaginationSupport listProcessEntitys(PaginationSupport page,Person verifier)
	{
		DetachedCriteria criteria = this.createQuery(getEntityClass());
		criteria.add(Restrictions.eq("verifer", verifier))
						.add(Restrictions.eq("flowstatus", Constrains.WORKFLOWPROCESS_STATE_PROCESS));
		return super.listByPage(criteria, page);
	}
	
	public PaginationSupport listFlowEntitys(PaginationSupport page,Person verifier,Integer[] flowstatus)
	{
		DetachedCriteria criteria = this.createQuery(getEntityClass());
		criteria.add(Restrictions.eq("verifer", verifier))
						.add(Restrictions.in("flowstatus", flowstatus));
		return super.listByPage(criteria, page);
	}
	
	@SuppressWarnings("unchecked")
	private Class<?> getEntityClass()
	{
		 return (Class<T>) ((ParameterizedType) getClass()
                 .getGenericSuperclass()).getActualTypeArguments()[0];
	}
}
